// @/utils/webSocket.js
import { Notification } from "element-ui";
import { getToken } from "./auth";
import store from '../store';

var socket = null;  // WebSocket实例对象
var lockReconnect = false;  // 是否真正建立连接
var timeout = 200 * 1000;  // 20秒一次心跳
var timeoutObj = null;  // 心跳倒计时
var serverTimeoutObj = null;  // 服务心跳倒计时
var timeoutnum = null;  // 断开重连倒计时

// 初始化WebSocket
const initWebSocket = async () => {
  if ("WebSocket" in window) {
    if (!store.state.user.id) {
      console.log("未登录！websocket工具获取不到userId");
    } else {
    //   const wsUrl = process.env.VUE_APP_SOCKET_SERVER + store.state.user.id;
      const wsUrl = `${process.env.VUE_APP_SOCKET_SERVER}${store.state.user.id}/${store.state.user.user.userType}`
      socket = new WebSocket(wsUrl);
      socket.onerror = webSocketOnError;
      socket.onmessage = webSocketOnMessage;
      socket.onclose = closeWebsocket;
      socket.onopen = openWebsocket;
    }
  } else {
    Notification.error({
      title: "错误",
      message: "您的浏览器不支持WebSocket，请更换Chrome或者Firefox",
    });
  }
};

// WebSocket连接建立成功
const openWebsocket = (e) => {
  start();
};

// 开始心跳检测
const start = () => {
  timeoutObj && clearTimeout(timeoutObj);
  serverTimeoutObj && clearTimeout(serverTimeoutObj);

  timeoutObj = setTimeout(function () {
    if (socket.readyState === 1) {
      // 如果连接正常，可以发送心跳消息（如果需要的话）
      // socket.send("heartbeat");
    } else {
      // 连接异常，尝试重连
      reconnect();
    }
    serverTimeoutObj = setTimeout(function () {
      // 超过时间未收到服务器的心跳消息，关闭连接
      socket.close();
    }, timeout);
  }, timeout);
};

// 重连
const reconnect = () => {
  if (lockReconnect) {
    return;
  }
  lockReconnect = true;
  timeoutnum && clearTimeout(timeoutnum);
  timeoutnum = setTimeout(function () {
    initWebSocket();
    lockReconnect = false;
  }, 1000);  // 延迟1秒后重新连接
};

// 重置心跳
const reset = () => {
  clearTimeout(timeoutObj);
  clearTimeout(serverTimeoutObj);
  start();  // 重启心跳
};

// 发送消息
const sendWebsocket = (message) => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(JSON.stringify(message));
  } else {
    console.error("WebSocket连接未打开，无法发送消息");
  }
};

// WebSocket连接错误处理
const webSocketOnError = (e) => {
  console.error("WebSocket连接出错", e,e.message );
  reconnect();
};

// WebSocket接收到消息
const webSocketOnMessage = (e) => {
 
  if (getToken()) {
    let data = JSON.parse(e?.data);
    if(data && data.length){
      console.log(data,9999);
      
      store.dispatch("initChats",data)
    }else{
      store.dispatch("setChatsMessage",data)
    }
  }
  reset();  // 重置心跳检测
};

// WebSocket关闭
const closeWebsocket = (e) => {
  console.log("WebSocket连接关闭");
  reconnect();
};

// 手动关闭WebSocket连接
const close = () => {
  if (socket) {
    socket.close();
  }
};

// 导出需要的方法
export default {
  initWebSocket,
  sendWebsocket,
  webSocketOnMessage,
  close,
};
